# ----------------------------------------------------------------------------
# pytform
# Copyright (c) 2008, Michael Henrique Siegwarth
# All rights reserved.
# 
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions 
# are met:
#
#  * Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#  * Redistributions in binary form must reproduce the above copyright 
#    notice, this list of conditions and the following disclaimer in
#    the documentation and/or other materials provided with the
#    distribution.
#  * Neither the name of pytform nor the names of its
#    contributors may be used to endorse or promote products
#    derived from this software without specific prior written
#    permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------

import os

import yaml
import pyglet
from pyglet.gl import *
from pyglet.window import key

class App(pyglet.window.Window):
    "The screen itself"
    def __init__(self):
        c = open("config.yaml")
        config = yaml.load(c.read())
        c.close()
        if config["screen"] == "fullscreen":
            super(App, self).__init__(fullscreen=True)
            self.screen_size = self.width, self.height
        else:
            super(App, self).__init__(width=config["screen"][0],
                                      height=config["screen"][1])

            self.screen_size = (config["screen"][0], config["screen"][1])

            # x and y position on screen
            self.set_location(5, 30)

        if config["vsync"] == False:
            self.set_vsync(False)

        # Schedule step function
        pyglet.clock.schedule_interval(self.game_step, 0.015)

        self.keys = key.KeyStateHandler()
        self.push_handlers(self.keys)
        self.pressed_modifiers = None

        # List of pressed keys
        self.pressed_keys = []
        self.pressed_modifiers = 0
  
        # Pixels per meter (zoom level)
        self.ppm = 50.0

        # The quantity, in pixels, that the map was moved
        self.map_offset = [0,0]
        
        # Pointer position (is updated each cycle)
        self.pointer_position = [0,0]

        # Clock to display the FPS
        self.fps_display = pyglet.clock.ClockDisplay()

        # Some extra OpenGL initialization
        glClearColor(0.4, 0.4, 0.4, 1)
        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

    def wireframe_mode(self, enable):
        if enable:
            glPolygonMode(GL_FRONT_AND_BACK , GL_LINE)
        else:
            glPolygonMode(GL_FRONT_AND_BACK , GL_FILL)

    def world_mode(self):
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        glOrtho(0, self.screen_size[0]/self.ppm, 0, self.screen_size[1]/self.ppm, -1, 1)
        glMatrixMode(GL_MODELVIEW)

    def normal_mode(self):
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        glOrtho(0, self.screen_size[0], 0, self.screen_size[1], -1, 1)
        glMatrixMode(GL_MODELVIEW)

    def on_draw(self):
        self.clear()

        self.world_mode()
        glTranslatef(self.map_offset[0], self.map_offset[1], 0)
        self.level.draw(self.map_offset)
        self.handle_world_draw()
        glTranslatef(-self.map_offset[0], -self.map_offset[1], 0)

        self.normal_mode()
        self.handle_normal_draw()

        glPushMatrix()
        glTranslatef(0.0, self.screen_size[1]-70, 0.0)
        self.fps_display.draw()
        glPopMatrix()

    def on_key_press(self, symbol, modifiers):
        self.handle_key_press(symbol)

        self.pressed_modifiers = modifiers

    def on_key_release(self, symbol, modifiers):
        self.pressed_modifiers = 0

    def on_mouse_motion(self, x, y, dx, dy):
        self.pointer_position[0] = x / self.ppm - self.map_offset[0]
        self.pointer_position[1] = y / self.ppm - self.map_offset[1]

    def on_mouse_press(self, x, y, button, modifiers):
        self.handle_mouse_down((x, y))

    def on_mouse_release(self, x, y, button, modifiers):
        self.handle_mouse_up((x, y))

    def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
        if buttons & pyglet.window.mouse.LEFT:
            self.handle_mouse_drag((x / self.ppm - self.map_offset[0],
                                    y / self.ppm - self.map_offset[1]),
                                   (dx / self.ppm, dy / self.ppm))
    
    def loop(self):
        pyglet.app.run()

    # All the commented methods must be implemented by subclasses

    #def handle_world_draw(self):
    #    pass

    #def handle_normal_draw(self):
    #    pass

    #def handle_key_press(self, symbol):
    #    pass

    #def handle_mouse_up(pos):
    #    pass

    #def handle_mouse_down(pos):
    #    pass

    #def handle_mouse_drag(pos, delta):
    #    pass
